<template>
  <div class="edit-event-page">
    <div class="page-header">
      <n-button quaternary @click="$router.back()">
        <n-icon :size="20">
          <ArrowBack />
        </n-icon>
      </n-button>
      <h1>编辑事件</h1>
      <div></div>
    </div>
    
    <div class="page-content">
      <n-spin :show="loading">
        <n-form
          v-if="event"
          ref="formRef"
          :model="form"
          :rules="rules"
          label-placement="top"
          @submit.prevent="handleSubmit"
        >
          <n-form-item path="title" label="事件标题">
            <n-input
              v-model:value="form.title"
              placeholder="请输入事件标题"
            />
          </n-form-item>
          
          <n-form-item path="description" label="事件描述">
            <n-input
              v-model:value="form.description"
              type="textarea"
              placeholder="请输入事件描述（可选）"
              :rows="3"
            />
          </n-form-item>
          
          <n-grid :cols="2" :x-gap="16">
            <n-grid-item>
              <n-form-item path="start_date" label="开始日期">
                <n-date-picker
                  v-model:value="startDateValue"
                  type="date"
                  placeholder="选择开始日期"
                  style="width: 100%"
                  @update:value="handleStartDateChange"
                />
              </n-form-item>
            </n-grid-item>
            
            <n-grid-item>
              <n-form-item path="start_time" label="开始时间">
                <n-time-picker
                  v-model:value="startTimeValue"
                  placeholder="选择开始时间（可选）"
                  style="width: 100%"
                  @update:value="handleStartTimeChange"
                />
              </n-form-item>
            </n-grid-item>
          </n-grid>
          
          <n-form-item path="priority" label="优先级">
            <n-select
              v-model:value="form.priority"
              placeholder="选择优先级"
              :options="priorityOptions"
            />
          </n-form-item>
          
          <!-- 动态表单字段 -->
          <div v-if="eventType && eventType.form_config">
            <div
              v-for="field in eventType.form_config.fields"
              :key="field.name"
              class="dynamic-field"
              v-show="!shouldHideField(field)"
            >
              <n-form-item :label="field.label">
                <!-- 文本输入 -->
                <n-input
                  v-if="field.type === 'text'"
                  v-model:value="form.extra_data[field.name]"
                  :placeholder="`请输入${field.label}`"
                />
                
                <!-- 多行文本 -->
                <n-input
                  v-else-if="field.type === 'textarea'"
                  v-model:value="form.extra_data[field.name]"
                  type="textarea"
                  :placeholder="`请输入${field.label}`"
                  :rows="3"
                />
                
                <!-- 数字输入 -->
                <n-input-number
                  v-else-if="field.type === 'number'"
                  v-model:value="form.extra_data[field.name]"
                  :placeholder="`请输入${field.label}`"
                  style="width: 100%"
                />
                
                <!-- 选择器 -->
                <n-select
                  v-else-if="field.type === 'select'"
                  v-model:value="form.extra_data[field.name]"
                  :placeholder="`请选择${field.label}`"
                  :options="getFieldOptions(field)"
                />

                <!-- 食物选择器 -->
                <FoodSelector
                  v-else-if="field.type === 'food_selector'"
                  v-model="form.extra_data[field.name]"
                  :placeholder="`请选择${field.label}`"
                />

                <!-- 饮食跟踪表单 -->
                <DietTrackingForm
                  v-else-if="field.type === 'food_intake_selector'"
                  v-model="form.extra_data[field.name]"
                />
              </n-form-item>
            </div>
          </div>
          
          <n-form-item>
            <n-space>
              <n-button type="primary" attr-type="submit" :loading="submitting">
                保存修改
              </n-button>
              <n-button @click="$router.back()">
                取消
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
        
        <div v-else class="not-found">
          <n-icon :size="64" color="#ccc">
            <Search />
          </n-icon>
          <p>事件不存在</p>
        </div>
      </n-spin>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ArrowBack, Search } from '@vicons/ionicons5'
import type { FormInst, FormRules } from 'naive-ui'
import { useEventsStore } from '@/stores/events'
import { formatDate } from '@/utils/date'
import type { Event, FormField } from '@/types'
import FoodSelector from '@/components/foods/FoodSelector.vue'
import DietTrackingForm from '@/components/DietTrackingForm.vue'

const route = useRoute()
const router = useRouter()
const eventsStore = useEventsStore()

// 表单引用
const formRef = ref<FormInst | null>(null)

// 状态
const loading = ref(false)
const submitting = ref(false)
const event = ref<Event | null>(null)

// 日期时间值
const startDateValue = ref<number | null>(null)
const startTimeValue = ref<number | null>(null)

// 表单数据
const form = reactive({
  title: '',
  description: '',
  start_date: '',
  start_time: '',
  priority: 'medium' as 'low' | 'medium' | 'high',
  extra_data: {} as Record<string, any>
})

// 事件ID
const eventId = computed(() => Number(route.params.id))

// 事件类型
const eventType = computed(() => {
  return event.value ? eventsStore.getEventType(event.value.event_type_id) : null
})

// 优先级选项
const priorityOptions = [
  { label: '低', value: 'low' },
  { label: '中', value: 'medium' },
  { label: '高', value: 'high' }
]

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入事件标题', trigger: 'blur' }
  ],
  start_date: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ]
}

// 处理开始日期变化
const handleStartDateChange = (value: number | null) => {
  if (value) {
    form.start_date = formatDate(new Date(value), 'YYYY-MM-DD')
  } else {
    form.start_date = ''
  }
}

// 处理开始时间变化
const handleStartTimeChange = (value: number | null) => {
  if (value) {
    const date = new Date(value)
    form.start_time = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:00`
  } else {
    form.start_time = ''
  }
}

// 获取字段选项
const getFieldOptions = (field: FormField) => {
  if (field.options) {
    return field.options.map(option => ({
      label: option,
      value: option
    }))
  }
  return []
}

// 判断是否应该隐藏字段
const shouldHideField = (field: any) => {
  // 隐藏饮食规划中的餐次和计划卡路里字段
  if (eventType.value?.name === '饮食规划') {
    return field.name === 'meal_type' || field.name === 'calories_planned'
  }
  return false
}

// 初始化表单数据
const initFormData = () => {
  if (!event.value) return

  form.title = event.value.title
  form.description = event.value.description || ''
  form.start_date = event.value.start_date
  form.start_time = event.value.start_time || ''
  form.priority = event.value.priority
  form.extra_data = event.value.extra_data ? { ...event.value.extra_data } : {}

  // 确保food_selector和food_intake_selector字段被正确初始化
  if (eventType.value?.form_config?.fields) {
    eventType.value.form_config.fields.forEach(field => {
      if (field.type === 'food_selector' && !form.extra_data[field.name]) {
        form.extra_data[field.name] = []
      } else if (field.type === 'food_intake_selector' && !form.extra_data[field.name]) {
        form.extra_data[field.name] = {
          meal_type: '',
          foods_intake: [],
          notes: ''
        }
      }
    })
  }

  // 设置日期时间选择器的值
  startDateValue.value = new Date(event.value.start_date).getTime()

  if (event.value.start_time) {
    const [hours, minutes] = event.value.start_time.split(':')
    const timeDate = new Date()
    timeDate.setHours(parseInt(hours), parseInt(minutes), 0, 0)
    startTimeValue.value = timeDate.getTime()
  }
}

// 移除handleDietTrackingSubmit，现在使用v-model直接绑定

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value || !event.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const updateData = {
      title: form.title,
      description: form.description,
      start_date: form.start_date,
      start_time: form.start_time,
      priority: form.priority,
      extra_data: form.extra_data
    }
    
    const result = await eventsStore.updateEvent(event.value.id, updateData)
    if (result) {
      window.$message?.success('事件更新成功')
      router.back()
    }
  } catch (error) {
    console.error('Update event error:', error)
  } finally {
    submitting.value = false
  }
}

// 获取事件详情
const fetchEventDetail = async () => {
  loading.value = true
  try {
    // 这里应该调用API获取事件详情
    // 暂时从store中查找
    const foundEvent = eventsStore.events.find((e: any) => e.id === eventId.value)
    event.value = foundEvent as Event || null
    
    if (event.value) {
      initFormData()
    }
  } catch (error) {
    console.error('Fetch event detail error:', error)
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(async () => {
  await eventsStore.init()
  await fetchEventDetail()
})
</script>

<style scoped>
.edit-event-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e0e0e0;
  background: white;
}

.page-header h1 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.page-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f5f5f5;
}

.page-content .n-form {
  max-width: 900px;
  margin: 0 auto;
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dynamic-field {
  margin-top: 16px;
}

.not-found {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.not-found p {
  margin-top: 16px;
  color: #666;
  font-size: 16px;
}

@media (max-width: 768px) {
  .page-header {
    padding: 12px 16px;
  }

  .page-content {
    padding: 12px;
  }

  .page-content .n-form {
    padding: 12px;
  }
}
</style>
